<?php

namespace App\Controller\Api\Trade;

use App\Base\BaseController4Restful;
use App\Entity\Trade\OrderPackTrade;
use App\Entity\Trade\OrderTrade;
use App\Repository\Common\CartRepository;
use App\Repository\Trade\OrderTradeRepository;
use App\Repository\Trade\ProductTradeRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class OrderTradeApiController extends BaseController4Restful
{
    /**
     * @Route("/api/orderTrades", name="apiGetOrderTrades",methods={"GET","POST"})
     */
    public function apiGetOrderTrades(OrderTradeRepository $repository,Request $request)
    {
        switch ($request->getMethod()) {
            case "POST":
                $data = $this->getRequestData();
                /**@var $OrderTrade OrderTrade*/
                $OrderTrade = $this->createEntity($data,OrderTrade::class);
                $this->myEm()->persist($OrderTrade);$this->myEm()->flush();
                return $this->json_out(1,"创建成功", $OrderTrade);
            default:
                $data       = $this->getRequestData();
                $per_page   = $data["limit"]??10;
                $page       = $data["page"]??1;
                $where      = $data['_where']??[];
                $search     = $data['_search']??[];
                $order      = $data["_order"]??["sort"=>"ASC"];
                //列表筛选
                $qb = $repository->createQueryBuilder("A");
                createWhere($qb,$where);
                createSearch($qb,$search,[],"or");
                createOrderBy($qb,$order);
                $qb->setFirstResult($page*$per_page - $per_page)->setMaxResults($per_page);
                $list = $qb->getQuery()->execute();
                $list= $this->normalize($list);
                return $this->json_out(1,"获取成功", $list);
        }
    }

    /**
     * @Route("/api/orderTrades/{id}", name="apiAddOrderTrades",methods={"GET","PUT","PATCH","DELETE"})
     */
    public function apiUpdateOrderTrades(OrderTrade $OrderTrade,Request $request)
    {
        $data = $this->getRequestData();
        switch ($request->getMethod()) {
            case "DELETE":
                $this->myEm()->remove($OrderTrade);$this->myEm()->flush();
                return $this->json_out(1,"已移除");
            case "PATCH":
            case "PUT":
                /**@var $OrderTrade OrderTrade*/
                $OrderTrade = $this->updateEntity($data,OrderTrade::class,$OrderTrade);
                break;
            case "Get":
            default:
        }
        $this->myEm()->persist($OrderTrade);$this->myEm()->flush();
        return $this->json_out(1,"获取成功", $OrderTrade);
    }

    /**
     * @Route("/api/orderTrades/create", name="ApiTradeOrderCreate")
     */
    public function ApiTradeOrderCreate(
        CartRepository $cartRepository,
        ProductTradeRepository $productTradeRepository
    )
    {
        $user = $this->needToBeUser();
        $req = $this->getRequestData();
        if (!$cart = $req["cart"]??[]) {
            return $this->json_out(0,"");
        }
        $phone = $req["phone"]??"";
        $address = $req["address"]??"";
        $tips = $req["tips"]??"";

        //更新用户手机号
//        if ($phone) {
//            $user->setPhone($phone);
//            $this->myEm()->persist($user);
//        }
        //设置订单信息
        $order = new OrderTrade();
        $order->setUser($user)
            ->setCreateAt(new \DateTime())
            ->setAddress($address)
            ->setStatus(0)
            ->setTips($tips);
        $this->myEm()->persist($order);
        $this->myEm()->flush();

        //创建包记录
        foreach ($cart as $row) {
            $id = $row["product"]["id"];
            $price = $row["product"]["price"];
            $num = $row["num"];
            $pack = $row["product"]["package"];
            $orderPackage = new OrderPackTrade();
            $orderPackage->setUser($user)
                ->setOrders($order)
                ->setTips("[$pack][$phone][$address]".$tips)
                ->setStatus(0)
                ->setPrice($price)
                ->setNum($num)
                ->setTotal($num * $price)
                ->setCreateAt(new \DateTime())
                ->setProduct($productTradeRepository->find($id));
            $this->myEm()->persist($orderPackage);
        }
        $this->myEm()->flush();
        return $this->json_out(1,"OK",$order);

    }
}
